const { body } = require("express-validator");
const validate = require("../middleware/validate");
const User = require("../models/userModel");
const md5 = require("../util/md5");

exports.register = validate([
  body("password")
    .notEmpty()
    .withMessage("密码不能为空")
    .isLength({ min: 8 })
    .withMessage("密码至少是8位"),
  // .matches(/\d/)
  // .withMessage("密码必须包含数字"),
  body("email")
    .notEmpty()
    .withMessage("电话不能为空")
    .bail()
    .custom(async (value) => {
      // 查询数据库中数据是否存在
      const user = await User.findOne({ email: value });
      if (user) {
        return Promise.reject("该邮箱已注册过");
      }
    }),
]);

exports.login = [
  validate([
    body("email").notEmpty().withMessage("邮箱不能为空"),
    body("password").notEmpty().withMessage("密码不能为空"),
  ]),
  // 验证用户是否存在
  validate([
    body("email").custom(async (email, { req }) => {
      const user = await User.findOne({ email }).select([
        "_id",
        "password",
        "name",
        "email",
        "portrait",
        "role",
        "company_id",
      ]);
      // 查询数据库查看数据是否存在
      if (!user) {
        return Promise.reject("用户不存在");
      }
      // 将数据挂载到请求对象中，后续的中间件也可以直接使用，就不需要重复查询了
      req.user = user;
    }),
  ]),
  // 验证密码是否正确
  validate([
    body("password").custom(async (password, { req }) => {
      if (md5(password) !== req.user.password) {
        return Promise.reject("密码错误");
      }
    }),
  ]),
];

exports.getUser = validate([validate.isValidObjectId(["params"], "userId")]);

exports.updateUser = [
  // 校验id是否是ObjectID
  validate([validate.isValidObjectId(["params"], "userId")]),
  // 校验更新的用户是否存在
  async (req, res, next) => {
    const userId = req.params.userId;
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).end();
    }
    next();
  },
];

exports.deleteUser = validate([validate.isValidObjectId(["params"], "userId")]);
